#include "task_queue.h"

static int queueSize = MAX_NUM;

cmsQueue_t *queue_create(int size)
{
	cmsQueue_t *handle = (cmsQueue_t *)malloc(sizeof(cmsQueue_t));
	if(handle == NULL){
		return NULL;
	}

	queueSize = size;
	handle->data = (data_t *)calloc(queueSize, sizeof(data_t));
	if(handle->data == NULL){
		free(handle);
		return NULL;
	}

	handle->front= handle->rear = 0;

	return handle;
}

int is_queue_empty(cmsQueue_t *qHandle)
{
	if(qHandle == NULL)
		return -1;

	return (qHandle->front == qHandle->rear ? 1 : 0 );
}

int is_queue_full(cmsQueue_t *qHandle)
{
	if(qHandle == NULL)
		return -1;

	return ((qHandle->rear + 1)%queueSize == qHandle->front? 1 : 0 );
}

int en_queue(cmsQueue_t *qHandle, data_t data)
{
	if(qHandle == NULL)
		return -1;

	if(is_queue_full(qHandle) == 1){
		return -1;
	}

	qHandle->data[qHandle->rear] = data;
	qHandle->rear = (qHandle->rear + 1)%queueSize;

	return 0;
}

int de_queue(cmsQueue_t *qHandle, data_t *data)
{
	if(qHandle == NULL)
		return -1;

	if(is_queue_empty(qHandle) == 1){
		return -1;
	}

	if(data != NULL)
		*data = qHandle->data[qHandle->front];

	qHandle->front = (qHandle->front + 1)%queueSize;

	return 0;
}

int destory_queue(cmsQueue_t *qHandle)
{
	if(qHandle != NULL){
		if(qHandle->data != NULL){
			free(qHandle->data);
		}
		free(qHandle);
	}

	return 0;
}

